<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1>智能家居控制中心</h1>
        <p>请登录您的账户</p>
      </div>
      
      <el-form 
        ref="loginFormRef" 
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="用户名或邮箱"
            size="large"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            size="large"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <el-button type="text" @click="showRegister = true">
          还没有账户？立即注册
        </el-button>
      </div>
    </div>
    
    <!-- 注册对话框 -->
    <el-dialog
      v-model="showRegister"
      title="用户注册"
      width="500px"
      :before-close="handleClose"
    >
      <el-form 
        ref="registerFormRef" 
        :model="registerForm" 
        :rules="registerRules" 
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="registerForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="registerForm.phone" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showRegister = false">取消</el-button>
        <el-button type="primary" :loading="registerLoading" @click="handleRegister">
          注册
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useAuthStore } from '../store/authStore.js'
import { useDeviceStore } from '../store/deviceStore.js'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserLogin',
  setup() {
    const authStore = useAuthStore()
    const deviceStore = useDeviceStore()
    
    const loginFormRef = ref()
    const registerFormRef = ref()
    const showRegister = ref(false)
    const loading = ref(false)
    const registerLoading = ref(false)
    
    // 登录表单
    const loginForm = reactive({
      username: '',
      password: ''
    })
    
    // 注册表单
    const registerForm = reactive({
      username: '',
      password: '',
      confirmPassword: '',
      email: '',
      nickname: '',
      phone: ''
    })
    
    // 登录验证规则
    const loginRules = {
      username: [
        { required: true, message: '请输入用户名或邮箱', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    }
    
    // 注册验证规则
    const registerRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== registerForm.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ]
    }
    
    // 处理登录
    const handleLogin = async () => {
      if (!loginFormRef.value) return
      
      await loginFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            const result = await authStore.login(loginForm)
            if (result.success) {
              ElMessage.success(result.message)
              // 登录成功后加载用户设备信息
              try {
                await deviceStore.loadUserDevices()
                console.log('设备信息加载完成')
              } catch (error) {
                console.warn('设备信息加载失败:', error)
                // 设备加载失败不影响登录流程
              }
              
              // 根据用户角色跳转到对应页面
              if (result.redirectPage) {
                console.log('准备跳转到页面:', result.redirectPage)
                console.log('用户角色:', result.userRole, '角色描述:', result.roleDescription)
                // 通过事件通知父组件进行页面跳转
                window.dispatchEvent(new CustomEvent('login-success', { 
                  detail: { 
                    redirectPage: result.redirectPage,
                    userRole: result.userRole,
                    roleDescription: result.roleDescription
                  } 
                }))
              }
            } else {
              ElMessage.error(result.message)
            }
          } catch (error) {
            ElMessage.error('登录失败：' + error.message)
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    // 处理注册
    const handleRegister = async () => {
      if (!registerFormRef.value) return
      
      await registerFormRef.value.validate(async (valid) => {
        if (valid) {
          registerLoading.value = true
          try {
            const result = await authStore.register(registerForm)
            if (result.success) {
              ElMessage.success(result.message)
              showRegister.value = false
              // 清空注册表单
              Object.keys(registerForm).forEach(key => {
                registerForm[key] = ''
              })
              
              // 根据用户角色跳转到对应页面
              if (result.redirectPage) {
                console.log('注册成功，准备跳转到页面:', result.redirectPage)
                console.log('用户角色:', result.userRole, '角色描述:', result.roleDescription)
                // 通过事件通知父组件进行页面跳转
                window.dispatchEvent(new CustomEvent('login-success', { 
                  detail: { 
                    redirectPage: result.redirectPage,
                    userRole: result.userRole,
                    roleDescription: result.roleDescription
                  } 
                }))
              }
            } else {
              ElMessage.error(result.message)
            }
          } catch (error) {
            ElMessage.error('注册失败：' + error.message)
          } finally {
            registerLoading.value = false
          }
        }
      })
    }
    
    // 关闭注册对话框
    const handleClose = () => {
      showRegister.value = false
      // 清空注册表单
      Object.keys(registerForm).forEach(key => {
        registerForm[key] = ''
      })
    }
    
    return {
      loginFormRef,
      registerFormRef,
      showRegister,
      loading,
      registerLoading,
      loginForm,
      registerForm,
      loginRules,
      registerRules,
      handleLogin,
      handleRegister,
      handleClose
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.login-header p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.login-form {
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 600;
}

.login-footer {
  text-align: center;
}

.login-footer .el-button {
  color: #409eff;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    padding: 30px 20px;
  }
  
  .login-header h1 {
    font-size: 24px;
  }
}
</style>
